package com.chapter4.graph.mst;

import com.chapter1.basic.bag.Bag;
import com.util.In;

/**
 * 
* @ClassName: WeightEdgeGraph 
* @Description: 权重边的图 
* @author minjun
* @date 2015年3月7日 下午4:26:07 
*
 */
public class WeightEdgeGraph {
	
	private Bag<Edge>[] bags;
	
	private Bag<Edge> edges;
	
	private int v;
	
	private int e; 

	@SuppressWarnings("unchecked")
	public WeightEdgeGraph(int v) {
		this.v=v;
		bags=(Bag<Edge>[])new Bag[v];
		edges=new Bag<Edge>();
		for(int i=0;i<v;i++){
			bags[i]=new Bag<Edge>();
		}
	}
	
	public WeightEdgeGraph(In in){
		this(in.readInt());
		int m=in.readInt();
		for(int i=0;i<m;i++){
			addEdge(new Edge(in.readInt(), in.readInt(), in.readDouble()));;
		}
	}
	
	public void addEdge(Edge edge){
		int a=edge.either();
		int b=edge.other(a);
		bags[a].add(edge);
		bags[b].add(edge);
		edges.add(edge);
		e++;
	}
	
	public Iterable<Edge> adj(int v){
		return bags[v];
	}
	
	public Iterable<Edge> edges(){
//		Bag<Edge> b=new Bag<Edge>();
//		for(int i=0;i<v;i++){
//			for(Edge e:adj(i)){
//				if(e.other(i)>i) b.add(e);
//			}
//		}
//		return b;
		return edges;
	}
	
	public int V(){
		return v;
	}
	
	public int E(){
		return e;
	}

	@Override
	public String toString() {
		StringBuilder sb=new StringBuilder();
		for(Bag<Edge> bag:bags){
			for(Edge e:bag){
				sb.append(e);
			}
			sb.append("\n");
		}
		return sb.toString();
	}

}
